<template>
  <a-card class="flex-1 overflow-auto pt-2" :body-style="{ padding: '0 8px', height: '100%', overflow: 'hidden' }">
    <div class="flex justify-between items-center mb-2">
      <a-button type="primary" @click="suitOpen = true">新增套餐</a-button>
      <div class="w-[500px] text-center truncate" :title="store.currentData?.lisRecord?.crisisLisMemo">{{ store.currentData?.lisRecord?.crisisLisMemo }}</div>
      <span class="w-24"></span>
    </div>
    <BaseTable
      bordered
      :loading="store.isLoading"
      :scroll="{ x: 1200 }"
      :data-source="store.currentData.lisRecordItemList || []"
      column-code="00001116"
      :extra-height="50"
      :exclude-columns="['crisisValue']"
      max-fill
      :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
    >
      <template #headerCell="{ column }">
        <template v-if="column.dataIndex === 'testResult'">
          <div class="flex justify-between">
            <div>结果</div>
            <div class="text-orange-500">提示</div>
          </div>
        </template>
      </template>
      <template #bodyCell="{ column, index, record }">
        <template v-if="column.dataIndex === 'xh'">
          <div class="flex justify-between">
            {{ index + 1 }}
            <RoundTag v-if="record.crisisStatus === '1'" bg-color="#f00">危</RoundTag>
          </div>
        </template>
        <template v-if="column.dataIndex === 'lisItemName'">
          <EditCell title="检验项目">
            <SelectTable
              v-model:value="record.lisItemName"
              :search-params="{ instrumentTypeId: store.currentInstrument.instrumentTypeId, xb: store.currentPatient?.brXb }"
              type="检验项目"
              @select="(selected) => onSelect(selected, record)"
            />
          </EditCell>
        </template>
        <template v-if="column.dataIndex === 'testResult'">
          <EditCell title="结果" class="relative">
            <BaseInput
              v-model:value="record.testResult"
              v-input-selection
              :auto-focus="focusKey === index"
              :disabled="store.currentPatient.status === '1'"
              placeholder="请输入"
              class="pr-8"
              :class="{
                'text-red-500': isOver(record.testResult, record.maxValue) || record.testResult === '阳',
                'text-green-500': isLower(record.testResult, record.minValue)
              }"
              @press-enter="onEnterResult(index)"
            />

            <div v-if="record.testResult" class="tip absolute right-4 text-2xl top-2 z-10">
              <div v-if="isOver(record.testResult, record.maxValue)" class="text-red-500">↑</div>
              <div v-else-if="isLower(record.testResult, record.minValue)" class="text-green-500">↓</div>
            </div>
          </EditCell>
        </template>
        <template v-if="column.dataIndex === 'lastResult'">
          <div v-if="record.lastResult === '阳性'" class="text-red-500">阳性</div>
          <div v-if="+record.lastResult < +record.minValue" class="text-green-500">{{ record.lastResult }}</div>
          <div v-if="+record.lastResult > +record.maxValue" class="text-red-500">{{ record.lastResult }}</div>
        </template>
        <!-- <template v-if="column.dataIndex === 'referValue' && record.minValue && record.maxValue">
          {{ `${record.minValue}~${record.maxValue}` }}
        </template> -->
        <template v-if="column.dataIndex === 'action'">
          <BaseButton type="link" size="small" :disabled="record.isNew" @click="onClickSpecial(record)">特殊参考值</BaseButton>
          <a-divider type="vertical" />
          <BaseButton confirm-text="确定删除?" type="text" size="small" danger @click="onDelete(record, index)">删除</BaseButton>
        </template>
      </template>
      <template #footer>
        <a-space class="flex justify-center">
          <a-button type="primary" ghost @click="onAdd"> 新增一行 </a-button>
          <a-button type="primary" @click="onSave">保存 </a-button>
        </a-space>
      </template>
    </BaseTable>
    <SpecialValue v-model:open="specialOpen" :row-data="rowData" @success="onSpecialSuccess" />
    <SuitModal v-model:open="suitOpen" @success="onSuitSuccess" />
  </a-card>
</template>

<script setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import BaseTable from '@/components/BaseTable'
import SelectTable from '@/components/SelectTable'
import useStore from '../store'
import SpecialValue from './SpecialValue.vue'
import SuitModal from './SuitModal.vue'

const emit = defineEmits(['save'])
const specialOpen = ref(false)
const suitOpen = ref(false)
const store = useStore()
const focusKey = ref(0)
const onAdd = () => {
  store.currentData.lisRecordItemList.push({ isNew: true })
}
const rowData = ref([])
const onClickSpecial = (row) => {
  specialOpen.value = true
  rowData.value = row
}
const onSpecialSuccess = (specialData) => {
  rowData.value.minValue = specialData.minValue
  rowData.value.maxValue = specialData.maxValue
  rowData.value.referValue = specialData.referValue
}
const isLower = (a, b) => Number(b) && Number(a) < Number(b)
const isOver = (a, b) => Number(b) && Number(a) > Number(b)
const onSelect = (selected, row) => {
  row.lisItemName = selected.itemName
  row.lisItemCode = selected.itemCode
  row.lisItemId = selected.id
  row.referValue = selected.referValue
  row.maxValue = selected.maxValue
  row.minValue = selected.minValue
  row.unit = selected.unit
}
const onDelete = async (row, idx) => {
  if (row.isNew) {
    store.currentData.lisRecordItemList.splice(idx, 1)
    // store.currentData.lisRecordItemList = store.currentData.lisRecordItemList.filter((item) => item.id !== row.id)
  } else {
    const { code, msg } = await post('/lis/LisRecord/doDelLisApplyItem', { id: row.id })
    if (code !== 0) return message.error(msg || '请求失败')
    message.success(msg || '删除成功')
    store.getOrderData()
  }
}
const onSave = () => {
  // store.currentData.lisRecordItemList = store.currentData.lisRecordItemList.filter((item) => !!item.id)
  emit('save')
}
const onSuitSuccess = (selects) => {
  const addRows = selects.map((select) => {
    return {
      isNew: true,
      ...select,
      lisItemId: select.itemId,
      lisItemName: select.itemName,
      lisItemCode: select.itemCode
    }
  })
  store.currentData.lisRecordItemList = [...store.currentData.lisRecordItemList, ...addRows]
}
const onEnterResult = (idx) => {
  if (idx < store.currentData.lisRecordItemList?.length - 1) {
    idx++
  } else {
    idx = 0
  }
  focusKey.value = idx
}
</script>
<style lang="less" scoped></style>
